<template>
	<div class="page relative">
		<global-header title="收款管理" @back="$router.back()" />
		<main class="page-main payment-main !overflow-hidden page">
			<div class="rounded-[10px]"></div>
			<van-tabs style="--van-tabs-line-height: 50px; --van-tabs-nav-background: transparent" color="#111111"
				title-active-color="#111111" title-inactive-color="#111111" v-model:active="state.payType">
				<van-tab v-for="(item, i) in bankTypeList" :key="i" :title="item.name" />
			</van-tabs>
			<div class="page-main mx-[15px] mt-[10px]">
				<div v-if="(state.payType == 3 && usdt.length > 0) || true" style="--van-field-label-margin-right: 0"
					class="!bg-white mt-[10px] rounded-[10px] px-[15px] pb-[30px] col justify-center items-center">
					<template v-if="state.payType == 0">
						<!-- <div class="mt-[32px] size-[184px] rounded-[10px] bg-[#F4F4F4] cursor-pointer">
						<img v-if="wechat.QrCode" :src="wechat.QrCode" class="size-full ">
						<div v-else class="size-full flex justify-center items-center">
							<van-icon name="plus" size="66px" color="#E0E0E0" />
						</div>
					</div> -->

						<div class="mt-[32px] size-[184px] rounded-[10px] bg-[#F4F4F4] cursor-pointer overflow-hidden">
							<van-uploader :ref="setUploaderRef(0)" v-model="wechat.QrCodes" @click="uploaderRefs[0].chooseFile()"
								:preview-full-image="false" :deletable="false" :max-count="1" preview-size="184" :after-read="e => {
									afterRead(e, wechat, 'QrCode');
								}
									">
								<div class="size-[184px] flex justify-center items-center">
									<van-icon name="plus" size="66px" color="#E0E0E0" />
								</div>
							</van-uploader>
						</div>
						<span class="mt-[21px] text-[14px] text-[#1111117b]">点击添加微信收款码</span>
						<span class="mt-[40px] w-full pl-[17px] text-[14px] text-[#111111]">微信号</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="wechat.BankNumber" placeholder="请输入微信号">
							<template #label></template>
						</van-field>
						<span class="mt-[15px] w-full pl-[17px] text-[14px] text-[#111111]">QQ号</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="wechat.Qq" placeholder="请输入QQ号">
							<template #label></template>
						</van-field>
					</template>
					<template v-else-if="state.payType == 1">
						<!-- <div class="mt-[32px] size-[184px] rounded-[10px] bg-[#F4F4F4] cursor-pointer">
						<img v-if="alipay.QrCode" :src="alipay.QrCode" class="size-full ">
						<div v-else class="size-full flex justify-center items-center">
							<van-icon name="plus" size="66px" color="#E0E0E0" />
						</div>
					</div> -->

						<div class="mt-[32px] size-[184px] rounded-[10px] bg-[#F4F4F4] cursor-pointer overflow-hidden">
							<van-uploader :ref="setUploaderRef(0)" v-model="alipay.QrCodes" @click="uploaderRefs[0].chooseFile()"
								:preview-full-image="false" :deletable="false" :max-count="1" preview-size="184" :after-read="e => {
									afterRead(e, alipay, 'QrCode');
								}
									">
								<div class="size-[184px] flex justify-center items-center">
									<van-icon name="plus" size="66px" color="#E0E0E0" />
								</div>
							</van-uploader>
						</div>

						<span class="mt-[21px] text-[14px] text-[#1111117b]">点击添加支付宝收款码</span>
						<span class="mt-[40px] w-full pl-[17px] text-[14px] text-[#111111]">支付宝账号</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="alipay.BankNumber" placeholder="请输入支付宝账号">
							<template #label></template>
						</van-field>
						<span class="mt-[15px] w-full pl-[17px] text-[14px] text-[#111111]">支付宝姓名</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="alipay.BankUsername" placeholder="请输入支付宝姓名">
							<template #label></template>
						</van-field>
					</template>
					<template v-else-if="state.payType == 2">
						<span class="mt-[30.5px] w-full pl-[17px] text-[14px] text-[#111111]">银行卡姓名</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="bank.BankUsername" placeholder="请输入银行卡姓名">
							<template #label></template>
						</van-field>

						<span class="mt-[15px] w-full pl-[17px] text-[14px] text-[#111111]">银行卡类型</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="bank.BankName" placeholder="请输入银行卡类型">
							<template #label></template>
						</van-field>

						<span class="mt-[15px] w-full pl-[17px] text-[14px] text-[#111111]">银行卡号</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="bank.BankNumber" placeholder="请输入银行卡号">
							<template #label></template>
						</van-field>

						<span class="mt-[15px] w-full pl-[17px] text-[14px] text-[#111111]">银行卡开户地址</span>
						<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
							:border="false" v-model="bank.BankAddress" placeholder="请输入银行卡开户地址">
							<template #label></template>
						</van-field>
					</template>
					<template v-else-if="state.payType == 3">
						<div v-for="(item, i) in usdt" :key="i" class="w-full col items-center">
							<div class="mt-[32px] size-[184px] rounded-[10px] bg-[#F4F4F4] cursor-pointer overflow-hidden">
								<van-uploader :ref="setUploaderRef(i)" v-model="item.QrCodes" @click="uploaderRefs[i].chooseFile()"
									:preview-full-image="false" :deletable="false" :max-count="1" preview-size="184" :after-read="e => {
										afterRead(e, item, 'QrCode');
									}
										">
									<div class="size-[184px] flex justify-center items-center">
										<van-icon name="plus" size="66px" color="#E0E0E0" />
									</div>
								</van-uploader>
							</div>
							<span class="mt-[21px] text-[14px] text-[#1111117b]">点击添加二维码</span>
							<span class="mt-[40px] w-full pl-[17px] text-[14px] text-[#111111]">虚拟币名称</span>
							<van-field @click="() => {
								usdtState.index = i;
								usdtState.value = item.BankName;
								usdtActionSelect?.handleShow();
							}
								" readonly class="!cursor-pointer mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]"
								right-icon="arrow-down" label-width="0" :border="false" v-model:model-value="item.BankName"
								placeholder="请选择虚拟币名称">
								<template #label></template>
							</van-field>
							<span class="mt-[15px] w-full pl-[17px] text-[14px] text-[#111111]">虚拟币地址</span>
							<van-field class="mt-[10px] !p-x[14px] !py-[9px] !bg-[#F6F9FE] rounded-[10px]" label-width="0"
								:border="false" v-model="item.BankNumber" placeholder="请输入虚拟币地址">
								<template #label></template>
							</van-field>
							<div v-if="i < usdt.length - 1" class="h-[1px] mt-[32px] w-full bg-[#F4F4F4]"></div>
						</div>
					</template>
				</div>
				<div v-if="state.payType == 3" @click="handleAddUsdt"
					class="mt-[10px] cursor-pointer bg-white rounded-[10px] text-[#333333] text-[14px] py-[20px] row items-center justify-center">
					<van-icon name="plus" size="24px" color="#333333" /> 添加
				</div>
			</div>
		</main>
		<div class="p-[15px]">
			<div class="flex gap-[10px]">
				<van-button @click="handleAwbSubmit" class="!flex-1 !bg-[#3976CC] !text-[#FFFFFF] rounded-[5px]" block>
					确认提交
				</van-button>
			</div>
		</div>
		<div class="w-[0] absolute overflow-hidden left-[-10px]">
			<ActionSelect ref="usdtActionSelect" v-model:val="usdtState.value" @update="() => {
				usdt[usdtState.index].BankName = usdtState.value;
			}
				" title="虚拟货币名称" :columns="usdtOptions" />
		</div>
	</div>
</template>
<route>
  {
    name: "admin-setting-payment",
    meta: {
      pageIndex: 3,
    }
  }
</route>
<script setup lang="ts">
import { toast } from "@/utils/toast";
import { cloneDeep } from "lodash-es";
import { reqPaymentMethods, reqPaymentMethodsEdit } from "@/api/setting";
import { useRoomStore } from "@/store/modules/room";
import { storeToRefs } from "pinia";
import { reqUploadImg } from "@/api/user";

const uploaderRefs = ref<Array<any>>([]);
const setUploaderRef = (index: number) => {
	return (el: any) => {
		uploaderRefs.value[index] = el;
	};
};

const roomStore = useRoomStore();
const { roomInfo } = storeToRefs(roomStore);
const state = reactive({
	tabActive: "base",
	payType: 0,
	loading: false
});
const usdtActionSelect = ref();

const usdtState = ref({
	value: "",
	index: 0
});
const usdtOptions = [
	{ text: "USDT-ERC20", value: "USDT-ERC20" },
	{ text: "USDT-TRC20", value: "USDT-TRC20" }
];
const bankTypeList = [
	{ name: "微信", value: 0 },
	{ name: "支付宝", value: 1 },
	{ name: "银行卡", value: 2 },
	{ name: "虚拟币", value: 3 }
];
const defaultPaymentData: PaymentMethodMo = {
	BankAddress: "",
	BankName: "",
	BankNumber: "",
	BankType: <1 | 2 | 3 | 4>1,
	BankUsername: "",
	CreatedAt: "",
	Id: 0,
	Qq: "",
	QrCode: "",
	RoomId: 1,
	UpdatedAt: ""
};

const wechat = ref<PaymentMethodMo | any>({
	...defaultPaymentData
});
const alipay = ref<PaymentMethodMo | any>({
	...defaultPaymentData,
	BankType: 2
});
const bank = ref<PaymentMethodMo | any>({
	...defaultPaymentData,
	BankType: 3
});
const usdt = ref<(PaymentMethodMo | any)[]>([]);

const baseForm = reactive<Partial<BasisConfigMo>>({
	SysImg: "",
	RoomNickname: "",
	ChatNickname: "",
	SysMinPrice: 1,
	IncomeExamine: 0,
	ShowWater: 0,
	Backwater: 0,
	GroupChat: 0,
	BetPop: 0,
	ShowForecast: 0,
	RoomAnnou: "",
	MiniApply: 0, // 会员最低上分
	MiniDown: 0, // 会员最多下分
	WithPwdErrCount: 0, // 下分密码可错次数
	SingleBetNotice: 0, // 单次下注预警金额值
	SingleWinNotice: 0, // 大额中奖预警值

	Status: 1,
	LhhStatus: 1, //  龙虎和结算方式         0返本 1通杀
	PlStatus: 1, //  游戏赔率              0关闭 1开启
	LsStatus: 1, // 会员流水              0关闭 1开启
	JpStatus: 1, // 微投键盘模式           0关闭 1开启
	XzStatus: 1, // 下注成功回复消息       0关闭 1开启
	SxfStatus: 1, // 允许重复上下分         0关闭 1开启
	DlbbStatus: 1, // 代理报表下线流水详情   0关闭 1开启
	FjggStatus: 1, // 房间公告栏             0关闭 1开启
	LowBalanceNobill: 1, // 低分数不发账单消息
	ShowFllow: 1,
	ShowPic1: 1,
	ShowPic2: 1,
	MustReply: 1, // 回复非订单指令消息0关闭 1回复
	SimplifyOrder: 1 // 订单内容简化显示 0关闭 1开启
});
const getParams = (obj: PaymentMethodMo) => {
	return {
		BankName: obj.BankName,
		BankNumber: obj.BankNumber,
		BankUsername: obj.BankUsername,
		BankAddress: obj.BankAddress,
		Qq: obj.Qq,
		QrCode: obj.QrCode
	};
};
const setBasisData = () => {
	if (roomInfo.value) {
		Object.keys(baseForm).forEach(key => {
			const typedKey = key as keyof typeof baseForm;
			if (typedKey in roomInfo.value! && roomInfo.value![typedKey] !== undefined) {
				(baseForm as any)[typedKey] = roomInfo.value![typedKey];
			}
		});
	}
};

const baseImgUrl = "https://f.shanshanim.vip/";

// 上传图片并发送图片消息
const afterRead: any = async (file: any, obj: any, key: string) => {
	const isIMAGE = file.file.type === "image/jpeg" || "image/jpg" || "image/png";
	// const isLt200K = file.file.size / 1024 < 200;

	if (!isIMAGE) {
		return toast.fail("上传文件只能是图片格式!");
	}
	// if (!isLt200K) {
	// 	return toast.fail("发送图片大小不能超过 200KB!");
	// }
	const loading = toast.loading("上传中...");
	try {
		let param = new FormData();
		param.append("ImgPath", file.file);
		let res = await reqUploadImg(param);
		console.log(res);
		obj[key] = baseImgUrl + res.data.ImgPath;
		obj[key + "s"] = [{ url: obj[key] }];
		console.log(obj);
		file.status = "done";
		loading.close();
	} catch (error) {
		loading.close();
		file.status = "failed";
		console.log(error);
	}
};

const getData = async () => {
	try {
		const res = await reqPaymentMethods();
		if (res.data.length) {
			console.log(res.data);
			const wechatData = res.data.find(item => item.BankType === 1)!;
			if (wechatData) {
				if (wechatData.QrCode) {
					wechatData.QrCode =
						(wechatData.QrCode.startsWith("http") ? "" : baseImgUrl) + wechatData.QrCode;
					(wechatData as any).QrCodes = [{ url: wechatData.QrCode }];
				} else {
					(wechatData as any).QrCodes = [];
				}
				wechat.value = wechatData;
			}
			const alipayData = res.data.find(item => item.BankType === 2)!;
			if (alipayData) {
				if (alipayData.QrCode) {
					alipayData.QrCode =
						(alipayData.QrCode.startsWith("http") ? "" : baseImgUrl) + alipayData.QrCode;
					(alipayData as any).QrCodes = [{ url: alipayData.QrCode }];
				} else {
					(alipayData as any).QrCodes = [];

				}

				alipay.value = alipayData;
				console.log(alipayData);
			}
			const bankData = res.data.find(item => item.BankType === 3)!;
			if (bankData) {
				if (bankData.QrCode) {
					bankData.QrCode = (bankData.QrCode.startsWith("http") ? "" : baseImgUrl) + bankData.QrCode;
					(bankData as any).QrCodes = [{ url: bankData.QrCode }];
				}
				else {
					(bankData as any).QrCodes = [];
				}
				bank.value = bankData;
			}
			usdt.value = res.data
				.filter(item => item.BankType === 4)
				.map((a: any) => {
					a.QrCodes = [
						{
							url: (a.QrCode.startsWith("http") ? "" : baseImgUrl) + a.QrCode
						}
					];
					return a;
				});
			console.log(usdt.value);
		}
	} catch (error) {
		console.log(error);
	}
};

const handleAwbSubmit = async () => {
	try {
		state.loading = true;
		let params = [getParams(defaultPaymentData)];
		if (state.payType == 0) {
			params = [cloneDeep(getParams(wechat.value))];
		}
		if (state.payType == 1) {
			params = [cloneDeep(getParams(alipay.value))];
		}
		if (state.payType == 2) {
			params = [cloneDeep(getParams(bank.value))];
		}
		if (state.payType == 3) {
			let isAdd = false;
			for (let i = 0; i < usdt.value.length; i++) {
				if (!usdt.value[i].BankName || !usdt.value[i].BankNumber) {
					isAdd = true;
					break;
				}
			}
			if (isAdd) {
				toast.info("请填写完整虚拟币信息");
				state.loading = false;
				return;
			}
			params = usdt.value.map(item => getParams(item));
		}
		await reqPaymentMethodsEdit({
			BankType: state.payType + 1,
			BankInfo: params
		});
		toast.success("更新成功");
		roomStore.actionRoomInfo().then(() => {
			setBasisData();
		});
		getData();
		state.loading = false;
	} catch (error) {
		state.loading = false;
		console.log(error);
	}
};

const handleAddUsdt = () => {
	let isAdd = false;
	for (let i = 0; i < usdt.value.length; i++) {
		if (!usdt.value[i].BankName || !usdt.value[i].BankNumber) {
			isAdd = true;
			break;
		}
	}
	if (isAdd) {
		toast.info("请填写完整虚拟币信息");
		return;
	}
	usdt.value.push({
		...defaultPaymentData,
		BankType: 4,
		QrCodes: []
	});
};
onMounted(() => {
	getData();
});
</script>

<style lang="scss" scoped>
.payment-main {
	background: url("@/assets/images/manage/bg.png") no-repeat;
	background-size: 100% auto;
	background-position: center -90px;

	:deep(.van-uploader) {

		&,
		.van-uploader__preview-image,
		.van-uploader__preview,
		.van-uploader__wrapper {
			width: 100% !important;
			height: 100% !important;
			flex: 1;
			margin: 0 !important;
		}
	}
}
</style>
